// pages/shops/shops.js
const BASE_URL = 'http://localhost:8080';

// 封装 wx.request 为 Promise
function wxRequest(options) {
  return new Promise((resolve, reject) => {
    wx.request({
      ...options,
      success: resolve,
      fail: reject
    });
  });
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners: [],
    categories: [
      { id: 0, name: '全部商品', type: null },
      { id: 1, name: '保健品', type: 0 },
      { id: 2, name: '药材', type: 1 },
      { id: 3, name: '器械', type: 2 },
      { id: 4, name: '手册', type: 3 }
    ],
    currentTab: 0,
    goodsList: [],
    currentPage: 1,
    totalPage: 1,
    pageSize: 8,
    searchText: '',
    isSearching: false,
    cartCount: 0,
    allProducts: []
  },

  onLoad() {
    this.fetchBanners();
    this.fetchProducts();
    this.updateCartBadge();
  },

  onShow() {
    this.updateCartBadge();
  },

  // 获取商品列表
  fetchProducts() {
    const type = this.getCurrentType();
    let url = `${BASE_URL}/products`;
    if (type !== null && type !== undefined) {
      url = `${BASE_URL}/products/type/${type}`;
    }
    wx.request({
      url: url,
      method: 'GET',
      success: (res) => {
        console.log('商品接口返回：', res);
        if (res.statusCode === 200 && res.data && res.data.data) {
          const allProducts = (res.data.data || []).map(item => ({
            ...item,
            img: item.coverImg,
            desc: item.introduce
          }));
          const totalPage = Math.ceil(allProducts.length / this.data.pageSize) || 1;
          const start = (this.data.currentPage - 1) * this.data.pageSize;
          const end = start + this.data.pageSize;
          this.setData({
            allProducts,
            goodsList: allProducts.slice(start, end),
            totalPage
          });
        } else {
          wx.showToast({
            title: '获取商品列表失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        console.log('商品接口请求失败：', error);
        console.error('获取商品列表失败:', error);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 搜索商品
  searchProducts() {
    if (!this.data.searchText.trim()) {
      this.fetchProducts();
      return;
    }
    wx.request({
      url: `${BASE_URL}/products/title/${this.data.searchText}`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data && res.data.data) {
          const allProducts = (res.data.data || []).map(item => ({
            ...item,
            img: item.coverImg,
            desc: item.introduce
          }));
          const totalPage = Math.ceil(allProducts.length / this.data.pageSize) || 1;
          const start = (this.data.currentPage - 1) * this.data.pageSize;
          const end = start + this.data.pageSize;
          this.setData({
            allProducts,
            goodsList: allProducts.slice(start, end),
            totalPage
          });
        } else {
          wx.showToast({
            title: '搜索失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        console.error('搜索商品失败:', error);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  getCurrentType() {
    return this.data.categories[this.data.currentTab].type;
  },

  onInputChange(e) {
    this.setData({ searchText: e.detail.value });
  },

  onSearch() {
    this.setData({ isSearching: true, currentPage: 1 }, () => {
      this.searchProducts();
    });
  },

  onTabChange(e) {
    this.setData({ 
      currentTab: e.currentTarget.dataset.index, 
      currentPage: 1, 
      isSearching: false, 
      searchText: '' 
    }, () => {
      this.fetchProducts();
    });
  },

  prevPage() {
    if (this.data.currentPage > 1) {
      const currentPage = this.data.currentPage - 1;
      const start = (currentPage - 1) * this.data.pageSize;
      const end = start + this.data.pageSize;
      this.setData({
        currentPage,
        goodsList: (this.data.allProducts || []).slice(start, end)
      });
    }
  },

  nextPage() {
    if (this.data.currentPage < this.data.totalPage) {
      const currentPage = this.data.currentPage + 1;
      const start = (currentPage - 1) * this.data.pageSize;
      const end = start + this.data.pageSize;
      this.setData({
        currentPage,
        goodsList: (this.data.allProducts || []).slice(start, end)
      });
    }
  },

  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/shops/shopsdetails/shopsdetail?id=${id}`
    });
  },

  addToCart(e) {
    const id = Number(e.currentTarget.dataset.id);
    let cart = wx.getStorageSync('cart') || [];
    let index = cart.findIndex(item => Number(item.id) === id);
    
    if (index > -1) {
      cart[index].num += 1;
    } else {
      const goods = this.data.goodsList.find(item => Number(item.id) === id);
      cart.push({ ...goods, num: 1 });
    }
    
    wx.setStorageSync('cart', cart);
    this.updateCartBadge();
    wx.showToast({
      title: '已添加到购物车',
      icon: 'success'
    });
  },

  buyNow(e) {
    const id = Number(e.currentTarget.dataset.id);
    const goods = this.data.goodsList.find(item => Number(item.id) === id);
    if (!goods) return;
    
    const tempOrder = [{
      id: Number(goods.id),
      title: goods.title,
      price: goods.price,
      img: goods.img,
      desc: goods.desc,
      num: 1,
      checked: true
    }];
    
    wx.setStorageSync('tempOrder', tempOrder);
    
    wx.navigateTo({
      url: '/pages/order/payment'
    });
  },

  goToCart() {
    wx.navigateTo({
      url: '/pages/shops/shopscart/shopscart'
    });
  },

  updateCartBadge() {
    let cart = wx.getStorageSync('cart') || [];
    const totalNum = cart.reduce((sum, item) => sum + item.num, 0);
    this.setData({
      cartCount: totalNum
    });
  },

  fetchBanners() {
    wx.request({
      url: `${BASE_URL}/products`, // 你可以根据实际情况换成专门的banner接口
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data && res.data.data) {
          const bannerIds = [1, 5, 7];
          const banners = res.data.data
            .filter(item => bannerIds.includes(item.id))
            .map(item => ({
              id: item.id,
              img: item.coverImg || item.img,
              title: item.title
            }));
          this.setData({ banners });
        } else {
          wx.showToast({ title: '轮播图加载失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '轮播图加载失败', icon: 'none' });
      }
    });
  }
})